package postgres

import (
	"context"
	"quipus/internal/database/model"

	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"

	"gorm.io/gorm/clause"
)

func (p *PGDB) UpsertKnotRelation(ctx context.Context, upsert *model.KnotRelation) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.KnotRelation.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "knot_id"}, {Name: "related_knot_id"}, {Name: "interact_type"}},
		DoUpdates: clause.AssignmentColumns([]string{"knot_id", "related_knot_id", "interact_type"}),
	}).Create(upsert)
	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListKnotRelations(ctx context.Context, find *apb.FindKnotRelation) ([]*model.KnotRelation, error) {
	p.query()
	knotRelation := q.WithContext(ctx).KnotRelation

	if find.KnotId != 0 {
		knotRelation = knotRelation.Where(q.KnotRelation.KnotID.Eq(find.KnotId))
	}

	if find.RelatedKnotId != 0 {
		knotRelation = knotRelation.Where(q.KnotRelation.RelatedKnotID.Eq(find.RelatedKnotId))
	}

	return knotRelation.Find()
}

func (p *PGDB) DeleteKnotRelation(ctx context.Context, delete *model.KnotRelation) error {
	p.query()
	knotRelation := q.WithContext(ctx).KnotRelation
	if delete.KnotID != 0 {
		knotRelation = knotRelation.Where(q.KnotRelation.KnotID.Eq(delete.KnotID))
	}

	if delete.RelatedKnotID != 0 {
		knotRelation = knotRelation.Where(q.KnotRelation.RelatedKnotID.Eq(delete.RelatedKnotID))
	}

	if delete.InteractType != "" {
		knotRelation = knotRelation.Where(q.KnotRelation.InteractType.Eq(delete.InteractType))
	}

	_, err := knotRelation.Delete()
	if err != nil {
		return err
	}

	return nil
}
